package com.typhoon.spring_shiro.utils;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * 验证码工具类
 * @author Typhoon
 * @date 2017-05-23 19:29
 * @since V2.0
 */
@Component
public class CaptchaUtil {

    @Autowired
    private Producer captchaProducer;

    /**
     * 生成验证码图片
     * 
     * @param request
     * @param response
     * @throws IOException
     */
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    /**
     * 获取验证码(服务器端)
     * 
     * @param request
     * @return
     */
    public static String getGeneratedCode(HttpServletRequest request) {
        return (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
    }
}
